import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    meta: { title: '登录', menuShow: false },
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/',
    name: 'Home',
    redirect: '/dashboard',
    component: Home,
    meta: { menuShow: false }
  },
  {
    path: '/',
    meta: { title: '首页', leaf: false, menuShow: true, iconCls: 'fa fa-home' },
    component: Home,
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard.vue'),
        meta: { title: '首页', menuShow: true }
      }
    ]
  },
  {
    path: '/',
    meta: { title: '用户列表', leaf: false, menuShow: true, iconCls: 'fa fa-user' },
    component: Home,
    children: [
      {
        path: '/user/list',
        name: 'UserList',
        component: () => import('@/views/user/list.vue'),
        meta: { menuShow: true, title: '用户列表' }
      }
    ]
  },
  {
    path: '/',
    meta: { title: '图书管理', iconCls: 'fa fa-book', menuShow: true },
    component: Home,
    children: [
      {
        path: '/book/list',
        name: 'BookList',
        meta: { title: '图书列表', menuShow: false },
        component: () => import('@/views/book/list.vue')
      },
      {
        path: '/book/category',
        name: 'BookCategory',
        meta: { title: '图书分类', menuShow: false },
        component: () => import('@/views/bookcategory/list.vue')
      }
    ]
  },
  {
    path: '/',
    meta: { title: '设置', iconCls: 'fa fa-cog', menuShow: true },
    component: Home,
    children: [
      {
        path: '/user/profile',
        name: 'Profile',
        meta: { title: '个人信息', menuShow: false },
        component: () => import('@/views/user/profile.vue')
      },
      {
        path: '/user/changePwd',
        name: 'Changepwd',
        meta: { title: '修改密码', menuShow: false },
        component: () => import('@/views/user/changePwd.vue')
      }
    ]
  },
  {
    path: '*',
    name: 'NotFound',
    meta: { menuShow: false },
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "notFound" */ '@/views/NotFound.vue')
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
  if (to.path.startsWith('/login')) {
    window.localStorage.removeItem('access_user')
    next()
  } else {
    const user = JSON.parse(window.localStorage.getItem('access_user'))
    if (user) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
